package org.xczy.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.xczy.core.entity.Menu;
import org.xczy.core.entity.User;
import org.xczy.core.entity.UserRole;
import org.xczy.core.mapper.UserMapper;
import org.xczy.core.mapper.UserRoleMapper;
import org.xczy.core.service.MenuService;
import org.xczy.core.service.UserService;
import org.xczy.core.utils.JWT;
import org.xczy.core.utils.MD5;
import org.xczy.core.vo.LoginVo;
import org.xczy.core.vo.UserVo;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【user】的数据库操作Service实现
* @createDate 2023-05-07 13:34:26
*/
@Log4j2
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

  @Resource
  private UserMapper userMapper;

  @Resource
  private RedisTemplate redisTemplate;

  @Resource
  private JWT jwt;

  @Resource
  private MenuService menuService;

  @Resource
  private UserRoleMapper userRoleMapper;

  @Override
  public Map<String, Object> login(LoginVo loginVo) {
    LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(User::getUsername, loginVo.getUsername());
    User loginUser= userMapper.selectOne(wrapper);
    if(loginUser == null || !loginUser.getPassword().equals(MD5.encrypt(loginVo.getPassword()))){
      return null;
    }
    log.info("请求密码：{}",MD5.encrypt(loginVo.getPassword()));
    log.info("查询密码：{}",loginUser.getPassword());
    loginUser.setPassword(null);
    String token = jwt.createToken(loginUser);
    redisTemplate.opsForValue().set(loginUser.getId().toString(), loginUser,30, TimeUnit.MINUTES);
    Map<String, Object> map = new HashMap<>();
    map.put("token", token);
    return map;
  }

  @Override
  public Map<String, Object> getUserInfo(String token) {
    User loginUser = null;
    try{
      loginUser = jwt.parseToken(token, User.class);
      if(loginUser != null){
        List<String> roleList = userMapper.getRoleNameByUserId(loginUser.getId());
        List<Menu> menuList = menuService.getMenuListByUserId(loginUser.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("name", loginUser.getUsername());
        map.put("avatar", loginUser.getAvatar());
        map.put("roles", roleList);
        map.put("menuList", menuList);
        return map;
      }
    }catch (Exception e){
      return null;
    }
    return null;
  }

  @Override
  public void logout(String token) {
    // todo 从cookie或者redis中清除用户信息
  }

  @Override
  public int addUser(UserVo userVo) {
    User user = new User(null,
        userVo.getUsername(),
        MD5.encrypt(userVo.getUsername()), // 默认新增用户的名称
        userVo.getEmail(),
        userVo.getPhone(),1,
        userVo.getAvatar(),0,null);
    try {
      int i = userMapper.insert(user);
      // 默认位普通员工
      userRoleMapper.insert(new UserRole(null, user.getId(), 3));
      return i;
    }catch (Exception e){
      System.out.println("用户添加失败：" + e);
      return 0;
    }
  }

  @Override
  public int updateUser(User user) {
    // todo 对邮箱、电话进行校验是否合法
    return userMapper.updateById(user);
  }

  @Override
  public User getUserById(Integer id) {
    try {
      User user = userMapper.selectById(id);
      LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
      wrapper.eq(UserRole::getUserId, id);
      List<UserRole> userRoleList = userRoleMapper.selectList(wrapper);
      List<Integer> roleIdList = userRoleList.stream()
          .map(UserRole::getRoleId)
          .collect(Collectors.toList());
      user.setRoleIdList(roleIdList);
      return user;
    }catch (Exception e){
      System.out.println("未查到");
      return null;
    }
  }

  @Override
  public int deleteUserById(Integer id) {
    try {
      int i = userMapper.deleteById(id);
      // 清除原有角色
      LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
      wrapper.eq(UserRole::getUserId, id);
      userRoleMapper.delete(wrapper);
      return i > 0 ? 1 : 0;
    }catch (Exception e){
      System.out.println("删除失败" + e);
    }
    return 0;
  }

}




